﻿using System;
using Newtonsoft.Json;
using ZilLion.Core.Unities.UnitiesMethods;
using ZilLion.Service.Core.ConfigManager.Manager;
using ZilLion.Service.WeChatMall.Domain.Repositorys.Interface;
using ZilLion.Service.WeChatMall.Domain.Responses;

namespace ZilLion.Service.WeChatMall.Domain.Repositorys
{
    public class GdMapRepository : IGdMapRepository
    {
        public ClientCityResponse GetCityInfoByIp(string ip)
        {
            var key = ZilLionConfigurationManager.GetConfigInstance<WechatMallConfig>().GaodeMapKey;
            var url = $"http://restapi.amap.com/v3/ip?key={key}&ip={ip}";
            try
            {
                var result = HttpHelper.HttpRequestGet<ClientCityResponse>(url);
                return result;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public MapSerchResponse SerchMap(string citycode, string keywords)
        {
            var key = ZilLionConfigurationManager.GetConfigInstance<WechatMallConfig>().GaodeMapKey;
            var url = citycode.IsNotNullOrEmpty()
                ? $"http://restapi.amap.com/v3/assistant/inputtips?output=json&city={citycode}&citylimit=true&keywords={keywords}&key={key}"
                : $"http://restapi.amap.com/v3/assistant/inputtips?output=json&keywords={keywords}&key={key}";

            var json = HttpHelper.HttpRequestGet(url);
            return JsonConvert.DeserializeObject<MapSerchResponse>(json);
        }

        public MapAllCitysDto GetAllCitys()
        {
            var key = ZilLionConfigurationManager.GetConfigInstance<WechatMallConfig>().GaodeMapKey;
            var url = $"http://restapi.amap.com/v3/config/district?keywords=中国&subdistrict=2&key={key}";
            var result = HttpHelper.HttpRequestGet<MapAllCitysDto>(url);
            return result;
        }

        public MapShortestPathDto GetShortestPath(string sourceLocation, string targetLocation)
        {
            var key = ZilLionConfigurationManager.GetConfigInstance<WechatMallConfig>().GaodeMapKey;
            var url =
                $"http://restapi.amap.com/v3/direction/driving?origin={sourceLocation}&destination={targetLocation}&strategy=2&extensions=all&key={key}";

            return HttpHelper.HttpRequestGet<MapShortestPathDto>(url);
        }
    }
}